<?php

namespace app\common\model;

use think\Model;
use think\Db;

/**
 * 分类模型
 */
class Goods extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    protected static function init()
    {
    }

    /**
     * 获取盲盒列表
    */
    public static function goods_list($goods_id = 0)
    {
        if ($goods_id > 0) {
            return model('goods')->where(['id' => $goods_id])->select();
        } else {
            return Goods::all();
        }
    }

    /**
     * 读取分类类型
     * @return array
     */
    public static function getTypeList()
    {
        $typeList = config('site.goods_categorytype');
        foreach ($typeList as $k => &$v) {
            $v = __($v);
        }
        return $typeList;
    }

    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['type'];
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    /**
     * 读取分类列表
     * @param string $type   指定类型
     * @param string $status 指定状态
     * @return array
     */
    public static function getCategoryArray($type = null, $status = null)
    {
        $list = collection(self::where(function ($query) use ($type, $status) {
            if (!is_null($type)) {
                $query->where('type', '=', $type);
            }
            if (!is_null($status)) {
                $query->where('status', '=', $status);
            }
        })->order('weigh', 'desc')->select())->toArray();
        return $list;
    }

    /**
     * 开盲盒
    */
    public static function draw_lottery($uid)
    {
        $coin_id = 3;//抽奖一次扣一次盲盒价格的USDT

        $list = self::goods_list();
        $lottery_pool = cache('lottery_pool');
        if (!$lottery_pool) {
            $min_probability = Db::name('goods')->where(['status' => 'normal'])->order('sub_probability asc')->value('sub_probability');
            $temp_num = (1 / $min_probability);
            $lottery_pool = [];
            foreach ($list as $item) {
                $pro = $item['sub_probability'] * $temp_num;
                for ($i = 0; $i < $pro; $i++) {
                    $lottery_pool[] = $item['id'];
                }
            }
            cache('lottery_pool', $lottery_pool, 86400);
        }
        $lottery_key = mt_rand(0, count($lottery_pool) - 1);
        $lottery_id = $lottery_pool[$lottery_key];

        //执行扣U动作
        $balance = User::get_balance($uid, $coin_id);
        $goods = self::get($lottery_id);
        if ($balance < $goods['price']) {
            return ['error' => 1, 'msg' => '您的余额不足'];
        }

        //写入订单
        $data = [
            'uid' => $uid,
            'goods_id' => $lottery_id,
            'name' => $goods['name'],
            'image' => $goods['image'],
            'price' => $goods['price'],
            'buy_coin_id' => $coin_id,
            'createtime' => time(),
            'updatetime' => time(),
            'status' => 'normal',
            'num' => 1
        ];
        $exist = Db::name('goods_order')->where(['uid' => $uid, 'goods_id' => $lottery_id])->find();
        if ($exist) {
            Db::name('goods_order')->where(['uid' => $uid, 'goods_id' => $lottery_id])->setInc('num', 1);
            $oid = $exist['id'];
        } else {
            $oid = Db::name('goods_order')->insertGetId($data);
        }
        Wallet::up_coin($uid, -$goods['price'], $coin_id, 'buy_box', $oid);

        return ['error' => 0, 'msg' => '抽奖成功', 'data' => $goods];
    }

    /**
     * 盲盒合成
    */
    public static function compose($uid, $ids)
    {
        $compose_ids = [];
        foreach ($ids as $goods_id) {
            $oid = Db::name('goods_order')->alias('o')->join('goods g', 'g.id=o.goods_id', 'left')->where(['o.uid' => $uid, 'o.goods_id' => $goods_id, 'g.is_compose' => 1])->value('o.id');
            if ($oid > 0) {
                $compose_ids[] = $oid;
            }
        }

        if (count($compose_ids) < 3 || count($compose_ids) > 5) {
            return ['error' => 1, 'msg' => '您的宠物数量不足，无法合成'];
        } else {
            switch (count($compose_ids)) {
                case 3:
                    $prize_id = 1;//赵长鹏
                    break;
                case 4:
                    $prize_id = 2;//V神
                    break;
                case 5:
                    $prize_id = 3;//中本聪
                    break;
                default:
                    $prize_id = 0;
                    break;
            }
            if ($prize_id == 0) {
                return ['error' => 1, 'msg' => '没有可以合成的选项'];
            }

            Db::startTrans();
            try {
                foreach ($compose_ids as $compose_id) {
                    Db::name('goods_order')->where(['id' => $compose_id])->setDec('num', 1);
                }
                $prize = Db::name('goods_prize')->where(['id' => $prize_id])->find();
                $data = [
                    'uid' => $uid,
                    'prize_id' => $prize_id,
                    'name' => $prize['name'],
                    'image' => $prize['image'],
                    'give_coin' => $prize['give_coin'],
                    'give_coin_type' => $prize['give_coin_type'],
                    'createtime' => time(),
                    'updatetime' => time(),
                    'status' => 'normal',
                    'num' => 1,
                ];
                $exist = Db::name('goods_prize_order')->where(['uid' => $uid, 'prize_id' => $prize_id])->find();
                if ($exist) {
                    Db::name('goods_prize_order')->where(['uid' => $uid, 'prize_id' => $prize_id])->setInc('num', 1);
                    $po_id = $exist['id'];
                } else {
                    $po_id = Db::name('goods_prize_order')->insertGetId($data);
                }
                if ($po_id > 0) {
                    $coin_id = 2;//赠送的是订单U价值的BNB
                    $money = Wallet::coin_price_transfer(3, $coin_id, $prize['give_coin']);
                    if ($money > 0) {
                        $res = Wallet::up_coin($uid, $money, $coin_id, 'compose_give', $po_id);
                        if ($res['error'] > 0) {
                            Db::rollback();
                            return ['error' => 1, 'msg' => $res['msg']];
                        }
                    }

                    Db::commit();
                    return ['error' => 0, 'msg' => '合成成功', 'data' => $data];
                } else {
                    Db::rollback();
                    return ['error' => 1, 'msg' => '生成订单失败'];
                }
            } catch (\Exception $exception) {
                Db::rollback();
                return ['error' => 1, 'msg' => $exception->getMessage()];
            }
        }
    }

    /**
     * 奖品列表
    */
    public static function prize_list($id = 0)
    {
        if ($id > 0) {
            return model('goods_prize')->where(['id' => $id])->select();
        } else {
            return GoodsPrize::getPrizeArray();
        }
    }
}
